<?php
/**
 *
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/7/12
 * @copyright PanxSoft Inc.
 */
namespace App\Services\Repositories;


use App\Models\Customer\Asset;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Collection as BaseCollection;

class AssetRepository
{
    protected $asset;

    public function __construct()
    {
        $this->asset = new Asset;
    }

    /**
     * @param Collection|Asset[] $assets
     *
     * @return BaseCollection
     */
    public static function groupAssetsByCategory(Collection $assets): BaseCollection
    {
        return $assets
            ->groupBy('category_id')
            // php assoc 与 index 数组的混合问题
            // [ '0' => 1 , 1 => 2, null, null, '2' => 3 ]
            // 为使前端数据结构保持一致不要返回前端 key 是 numeric 的 assoc 数组
            ->map(function (Collection $assets_group, $cate_id) {
                return [
                    'category_id' => $cate_id,
                    'assets' => $assets_group,
                ];
            })
            // 保证返回是对象的数组集合，无 category_id key 值
            ->values();
    }

    /**
     * @test
     * @param Asset $asset
     *
     * @return array
     */
    public static function destroyRelations(Asset $asset): array
    {
        $deletes = [];

        $deletes['products'] = $asset->products()->update(['asset_id' => 0]);

        $deletes['packs'] = $asset->packs()->detach();

        $deletes['asset_pivot_products'] = $asset->assetPivotProducts()->detach();

        return $deletes;
    }
}